/* TurboTextField.m
 *
 *   TurboTextField is a subclass of TextField which installs
 * the TurboTFCell class as it's Cell class.  It also overrides
 * textDidGetKeys:isEmpty: in order to support "length watching"
 * and the ability to restore the previous text after a paste has
 * failed because it is too long.
 * 
 *
 * You may freely copy, distribute, and reuse the code in this example.
 * NeXT disclaims any warranty of any kind, expressed or  implied, as to its
 * fitness for any particular use.
 *
 * Written by:  Sharon Zakhour 
 * Created:  Oct/91
 */

#import "TurboTextField.h"
#import "TurboTFCell.h"
#include <appkit/Text.h>
#import <appkit/Application.h>
#import <appkit/Panel.h>
#import <dpsclient/dpsclient.h>
#import <appkit/nextstd.h>
#import <strings.h> 
#import <appkit/publicWraps.h>

@implementation TurboTextField

+ initialize
{
    if (self == [TurboTextField class])
    {
	[super initialize];
	[TurboTextField setCellClass:[TurboTFCell class]];
    }
    return self;
}

- setMaxLength: (int) length
{
    return [cell setMaxLength: length];
}

- setAutoJump: (BOOL) flag forLength: (int)length
{
    return [cell setAutoJump: flag forLength: length];
}

- setAcceptsReturn: (BOOL) flag
{
    return [cell setAcceptsReturn: flag];
}

- setCustomFilter: (NXTextFilterFunc)aFilter
{
    return [cell setCustomFilter: aFilter];
}

#define TOO_LONG		1
#define ILLEGAL_STRING	2

- textDidGetKeys:sender isEmpty:(BOOL)flag
{
    int oldLen, error = 0;
    char	 *temp;
    
    if (!flag)
    {
	temp = malloc([cell maxLength] + 1);
	[sender getSubstring:temp start:0 length:[cell maxLength]];
	temp[[cell maxLength]] = '\0';

	// First check to see if the string is too long.  This will only
	// occur when pasting since the text and character filters
	// handle keyboard entry.
	if ([cell maxLength] && [sender textLength] > [cell maxLength])
	{
	    error = TOO_LONG;
	}
	
	// Next, run this text through the filter.  This will
	// catch any illegally formatted paste.
	if ([cell checkString: temp] == NO)
	{
	    error = ILLEGAL_STRING;
	}

	switch (error)
	{
	case 0:
	    // No error -- so save current input text and return
	    [cell setOriginalText: temp];
	    return self;
	case TOO_LONG:
	    NXBeep();
	    NXRunAlertPanel (NULL,  "String too long...","OK", NULL, NULL);
	    break;
	case ILLEGAL_STRING:
	    NXBeep();
	    NXRunAlertPanel (NULL,  "Illegally formatted string...","OK", NULL, NULL);
	    break;
	}
	
	// Now replace the original text (because an error was encountered)
	[sender setSel: 0 : [sender textLength]];
	oldLen = strlen([cell originalText]);
	if (oldLen)
	    [sender replaceSel : [cell originalText]];
	else
	    [sender replaceSel: ""];
	[sender setSel: oldLen: oldLen];
    }
    
    // If a delegate has been installed, let it have a crack at this...
    [super textDidGetKeys: sender isEmpty: flag];
    return self;
}

@end
